import API from "../../http/api.js"
import async from "../../general/async.js"

function router() {
    this.routerMap = new Map()
}

router.prototype = new async()
router.prototype.constructor = router
router.prototype.init = function (path = undefined) {
    path = (path === undefined) ? process.env.VUE_APP_ROUTER : path;
    if (path !== undefined) {
        ++this.waitTask;
        API.getContext(path).then((response) => {
            let router_cfg = response.data
            if (router_cfg != undefined) {
                this.target = this
                for (let o in router_cfg) {
                    if (!this.routerMap.has(o)) {
                        this.routerMap.set(o, router_cfg[o])
                    } else {
                        throw new Error(`[router] ${o} property is ready.`)
                    }
                }
                --this.waitTask
            } else {
                throw new Error(`[router] require 'public/router/${path}' error.`)
            }
        }).catch((error) => {
            throw error
        })
    }else{
        throw new Error(`[router] init path is undefined.`)
    }
    return this
}

router.prototype.add = function (key, compileSource) {
    if (!this.routerMap.has(key)) {
        this.routerMap.set(key, compileSource)
    } else {
        throw new Error(`[router] router map has ${key}.`)
    }
}

router.prototype.delete = function (key) {
    if (this.routerMap.has(key)) {
        this.routerMap.delete(key)
    }
}
router.prototype.get = function (key) {
    console.log(this.routerMap)
    let result = this.routerMap.get(key)
    console.log(result);
    if (result == undefined) {
        throw new Error(`[router] can not found ${key} in router map.`)
    } else {
        return result
    }
}

router.prototype.hitByUrl = function () {
    if (location != undefined) {
        if (location.href.indexOf("?") == -1 || location.href.indexOf('k=') == -1) {
            return "default"
        }
        else {
            let queryString = location.href.substring(location.href.indexOf('?') + 1)
            let parameters = queryString.split("&")
            let pos, paraName, paraValue
            for (let o = 0; o <= parameters.length; o++) {
                pos = parameters[o].split('=')
                if (pos == -1) { continue }
                paraName = pos[0]
                paraValue = pos[1]
                if (paraName == 'k') {
                    return decodeURIComponent(paraValue.replace(/\+/g, ""))
                }
            }
            return undefined
        }
    } else {
        throw new Error(`[router] hitByUrl location context is null.`)
    }
}

const R = new router()

export default R

